package middleware

import (
	"github.com/gin-gonic/gin"
	"vpn/app/global"
	"vpn/app/global/consts"
	"vpn/app/utils/jwt_token"
	"vpn/app/utils/response"
)

func AuthJwtToken(ctx *gin.Context) {
	claims, code := jwt_token.ValidateJwtToken(ctx)
	if code == consts.JwtTokenInvalid {
		response.Fail(ctx, 400, "jwtToken验证失败", gin.H{})
		return
	}
	// token接近过期
	if code == consts.JwtTokenCloseExpire {
		token, err := claims.RefreshToken(global.JwtConf.JwtExpireAt)
		if err != nil {
			response.Fail(ctx, 500, "jwtToken更新失败", gin.H{"error": err.Error()})
			return
		}
		ctx.Writer.Header().Set("new-token", token)
	}
	ctx.Next()
}
